﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Security;
using Work.BL.Managers;

namespace Work.UI.Web.Forms.Code.Security
{
    public class FormsSecurityService : ISercurityService
    {
        #region Fields

        private readonly IUserManager _userManager;

        #endregion

        #region Constructors

        public FormsSecurityService(IUserManager userManager)
        {
            this._userManager = userManager;
        }

        #endregion

        #region ISercurityService Members

        public bool Login(string userName, string password, bool remember = false)
        {
            string _userName = userName;
            if(!this._userManager.IsValid(_userName,password))
            {
                return false;
            }
            DefinePrincipal(_userName);
            FormsAuthentication.SetAuthCookie(_userName, remember);
            return true;
        }

        public void RefreshPrincipal()
        {
            IPrincipal principal = HttpContext.Current.User;
            if (principal != null && principal.Identity != null && principal.Identity.IsAuthenticated)
            {
                DefinePrincipal(principal.Identity.Name);
            }
        }

        public void Logout()
        {
            FormsAuthentication.SignOut();
            HttpContext.Current.User = null;
        }

        public bool IsAuthotificate()
        {
            IPrincipal principal = HttpContext.Current.User;
            if (principal != null && principal.Identity != null && principal.Identity.IsAuthenticated)
            {
                return true;
            }
            return false;
        }

        #endregion

        #region Helpers

        private void DefinePrincipal(string userName)
        {
            IIdentity identity = new GenericIdentity(userName);
            string[] roles = this._userManager.GetUserRoles(userName);
            HttpContext.Current.User = new GenericPrincipal(identity, roles);
        }

        #endregion

    }
}